<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="welcome" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    类加载：双亲委派机制 |  ChenyyのBlog
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">
  
<link rel="stylesheet" href="/css/custom.css">

  
  <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-Java/类加载：双亲委派机制"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  类加载：双亲委派机制
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2021/05/22/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD%EF%BC%9A%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%9C%BA%E5%88%B6/" class="article-date">
  <time datetime="2021-05-22T12:21:58.000Z" itemprop="datePublished">2021-05-22</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java/">Java</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.9k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">6 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <ul>
<li>类的生命周期</li>
<li>类加载器</li>
<li>双亲委派机制</li>
</ul>
<span id="more"></span>

<h1 id="类的生命周期"><a href="#类的生命周期" class="headerlink" title="类的生命周期"></a>类的生命周期</h1><p>类从被加载到虚拟机开始，到卸载出内存为止，它的整个的生命周期包括：<strong>加载、连接（验证、准备、解析）、初始化、使用和卸载七个阶段</strong>。</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210522163534.png"></p>
<h3 id="加载过程"><a href="#加载过程" class="headerlink" title="加载过程"></a><strong>加载过程</strong></h3><p>将编译之后的Class文件（Java字节码）加载至虚拟机内存中，并存储在方法区。</p>
<h3 id="连接过程"><a href="#连接过程" class="headerlink" title="连接过程"></a><strong>连接过程</strong></h3><p>连接被分为了验证、准备、解析三部分。</p>
<p>验证：Class文件中的字节信息是否符合Java虚拟机的要求，是否安全（可能会做出危害虚拟机的行为）。</p>
<p>准备：创建类或接口的静态变量，为类变量分配内存，并设置类变量的初始值。不包含实例变量的内存，实例变量的内存将会被分配到堆中。</p>
<blockquote>
<p>这里的初始值指的是数据类型的零值，并非程序员设置的值，比如static int i = 1;此时得到的i是0，赋值为1将会在初始化阶段执行。</p>
</blockquote>
<p>解析：将常量池中的符号引用替换为直接引用（内存地址）。</p>
<blockquote>
<p>a.run();代码表示对A类的run()方法的<code>符号引用</code>，由run()方法的全名 和 相关描述符组成。</p>
<p>解析阶段，Java虚拟机会把这个符号引用替换为一个指针，该指针指向A类的run()方法在方法区的内存位置，这个指针就是<code>直接引用</code>。</p>
</blockquote>
<h3 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a><strong>初始化</strong></h3><p>前面的类加载过程中，除了通过自定义类加载器参与之外，其余的动作其实都是由虚拟机主导和控制的。</p>
<p><strong>初始化是类加载的最后一步</strong>，真正开始执行程序中代码的步骤，比如将i赋值为1的过程，初始化类变量，加载类的静态语句块的过程。</p>
<p>在准备阶段赋值过一次了，那次赋值是系统要求的初始值，跟我们个人的设定无关，而<strong>初始化的赋值才是真正根据程序员设计而主导的初始化</strong>。</p>
<h3 id="使用和卸载"><a href="#使用和卸载" class="headerlink" title="使用和卸载"></a><strong>使用和卸载</strong></h3><p>使用类的阶段就是new对象的过程，我们会使用到各种类型对象，以及使用完毕对这个类型的卸载，卸载一般发生在程序关闭的时候。</p>
<p>程序正常执行结束、遇到异常关闭、或者操作系统出问题导致程序关闭这些都会卸载这些类的加载。</p>
<h1 id="类加载器"><a href="#类加载器" class="headerlink" title="类加载器"></a>类加载器</h1><p>从JVM的角度看，<strong>类加载器主要有两类：</strong></p>
<ul>
<li>Bootstrap ClassLoader和其他类加载，Bootstrap ClassLoader是C++语言实现，是虚拟机自身的一部分；</li>
<li>其他类加载器都是Java语言实现，不属于虚拟机，全部继承自抽象类java.lang.ClassLoader</li>
</ul>
<p>从Java开发者的角度看，需要了解类加载器的双亲委派模型，如下图所示：</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210522182000.png"></p>
<h3 id="启动类加载器Bootstrap-ClassLoader"><a href="#启动类加载器Bootstrap-ClassLoader" class="headerlink" title="启动类加载器Bootstrap ClassLoader"></a><strong>启动类加载器Bootstrap ClassLoader</strong></h3><p>这个类加载器将负责存放在/lib目录中，并且是虚拟机会识别的jar类库加载到内存中。更直白点说，就是我们常用的java.lang开头的那些类，一定是被Bootstrap ClassLoader加载的</p>
<h3 id="扩展类加载器Extension-ClassLoader"><a href="#扩展类加载器Extension-ClassLoader" class="headerlink" title="扩展类加载器Extension ClassLoader"></a><strong>扩展类加载器Extension ClassLoader</strong></h3><p>它负责加载/lib/ext目录中的、或者被java.ext.dirs系统变量指定的路径中的所有类库。</p>
<h3 id="应用程序类加载器Application-ClassLoader"><a href="#应用程序类加载器Application-ClassLoader" class="headerlink" title="应用程序类加载器Application ClassLoader"></a><strong>应用程序类加载器Application ClassLoader</strong></h3><p>它负责加载用户CLASSPATH环境变量指定的路径中的所有类库。如果应用程序中没有自定义过自己的类加载器，这个就是一个Java程序中默认的类加载器。</p>
<h3 id="用户自定义的类加载器"><a href="#用户自定义的类加载器" class="headerlink" title="用户自定义的类加载器"></a><strong>用户自定义的类加载器</strong></h3><p>用户在需要的情况下，可以实现自己的自定义类加载器，一般而言，在以下几种情况下需要自定义类加载器</p>
<ul>
<li><strong>隔离加载类。</strong>某些框架为了实现中间件和应用程序的模块的隔离，就需要中间件和应用程序使用不同的类加载器</li>
<li><strong>修改类加载的方式</strong>。类加载的双亲委派模型并不是强制的，用户可以根据需要在某个时间点动态加载类</li>
<li><strong>扩展类加载源</strong>，例如从数据库、网络进行类加载</li>
<li><strong>防止源代码泄露</strong>。Java代码很容易被反编译和篡改，为了防止源码泄露，可以对类的字节码文件进行加密，并编写自定义的类加载器来加载自己的应用程序的类</li>
</ul>
<h1 id="双亲委派机制"><a href="#双亲委派机制" class="headerlink" title="双亲委派机制"></a>双亲委派机制</h1><h3 id="向上委托查找，向下委托加载"><a href="#向上委托查找，向下委托加载" class="headerlink" title="向上委托查找，向下委托加载"></a><strong>向上委托查找，向下委托加载</strong></h3><p>如果一个类加载器收到了类加载的请求，不考虑们自定义类加载器，首先会在AppClassLoader中检查是否加载过，如果有那就无需再加载了。如果没有就把请求委托给父加载器去完成，依次向上。</p>
<p>因此，所有的类加载请求最终都被传递到顶层的启动类加载器BootstrapClassLoader。这时候开始考虑自己是否能加载了，如果在它的搜索范围中没有找到所需的类时，会下沉到子加载器去加载，一直到最底层，如果没有任何加载器能加载，就会抛出ClassNotFoundException。</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210522194631.png"></p>
<h3 id="源码"><a href="#源码" class="headerlink" title="源码"></a><strong>源码</strong></h3><p>“java.lang”包下的<strong>ClassLoader</strong>类中<strong>loadClass</strong>方法代码如下：</p>
<pre><code>public Class&lt;?&gt; loadClass(String name) throws ClassNotFoundException &#123;
    return loadClass(name, false);
&#125;
//              -----??-----
protected Class&lt;?&gt; loadClass(String name, boolean resolve)
    throws ClassNotFoundException
&#123;
        // 首先，检查是否已经被类加载器加载过
        Class&lt;?&gt; c = findLoadedClass(name);
        if (c == null) &#123;
            try &#123;
                // 存在父加载器，递归的交由父加载器
                if (parent != null) &#123;
                    c = parent.loadClass(name, false);
                &#125; else &#123;
                    // 直到最上面的Bootstrap类加载器
                    c = findBootstrapClassOrNull(name);
                &#125;
            &#125; catch (ClassNotFoundException e) &#123;
                // ClassNotFoundException thrown if class not found
                // from the non-null parent class loader
            &#125;
 
            if (c == null) &#123;
                // If still not found, then invoke findClass in order
                // to find the class.
                c = findClass(name);
            &#125;
        &#125;
        return c;
&#125;
</code></pre>
<h3 id="双亲委派机制的作用"><a href="#双亲委派机制的作用" class="headerlink" title="双亲委派机制的作用"></a><strong>双亲委派机制的作用</strong></h3><p>1、避免类的重复加载。通过委托去向上面问一问，加载过了，就不用再加载一遍。保证数据安全。</p>
<p>2、保护程序安全，保证核心类不能被篡改。通过委托方式，不会去篡改核心.class，即使篡改也不会去加载，即使加载也不会是同一个.class对象了。不同的加载器加载同一个.class也不是同一个Class对象。这样保证了Class执行安全。</p>
<ul>
<li>自定义类：java.lang.String (没用) </li>
<li>自定义类：java.lang.ShkStart（报错：阻止创建 java.lang开头的类）</li>
</ul>
<p>为了系统类的安全，类似java.lang.String这种，jvm需要保证 Java 应用所使用的都是同一个版本的 Java 核心库的类，是互相兼容的。系统的类已经被Bootstrap classLoader加载过了，所以其他类加载器并没有机会再去加载，从一定程度上防止了危险代码的植入。</p>
<p>如果我们有一个类想要通过自定义的类加载器来加载，可以通过重写ClassLoader中的loadClass方法，实现自定义类加载器。改变类的类加载器的时候要注意，如果全部改了，找不到Object.class这种顶级类，就加载不了了。</p>
<p>参考：</p>
<p>通俗易懂的双亲委派机制：<a target="_blank" rel="noopener" href="https://blog.csdn.net/codeyanbao/article/details/82875064">https://blog.csdn.net/codeyanbao/article/details/82875064</a></p>
<p>Java 符号引用 与 直接引用：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/mzzcy/p/7223405.html">https://www.cnblogs.com/mzzcy/p/7223405.html</a></p>
<p>如何破坏双亲委派：<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/k0_K627ENyHeE92vW5HIiw">https://mp.weixin.qq.com/s/k0_K627ENyHeE92vW5HIiw</a></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2021/05/22/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD%EF%BC%9A%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%9C%BA%E5%88%B6/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java/" rel="tag">Java</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2021/05/23/Java/Java%E8%99%9A%E6%8B%9F%E6%9C%BA%E5%86%85%E5%AD%98%E7%BB%93%E6%9E%84(JVM)/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Java虚拟机内存结构（JVM）
          
        </div>
      </a>
    
    
      <a href="/2021/05/21/Mysql/MVCC%E5%A4%9A%E7%89%88%E6%9C%AC%E5%B9%B6%E5%8F%91%E6%8E%A7%E5%88%B6/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">MVCC多版本并发控制</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2021
        <i class="ri-heart-fill heart_icon"></i> Chenyy
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="ChenyyのBlog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">文章</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/book">收藏</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about/me">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>